package spikemodel

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"web_server/model"
)

func GetFruitModel() (fl []string) {
	if err := model.DBSlaveRand().Select(&fl, "SELECT name FROM t_fruit_species where rest > 0"); err != nil {
		panic(err)
	}
	return
}

func GetSpikeCheck(id int64) *map[string]interface{} {
	res, err := http.Get("http://127.0.0.1:7013/check/" + strconv.FormatInt(id, 10))
	if err != nil {
		return nil
	}
	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		panic(err)
		return nil
	}
	var ret = new(map[string]interface{})
	if err := json.Unmarshal(body, ret); err != nil {
		panic(err)
		return nil
	}
	return ret
}

func GetSpikeInsert(data []byte) *map[string]interface{} {
	res, err := http.Get("http://127.0.0.1:7013/insert/" + string(data))
	if err != nil {
		return nil
	}
	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		panic(err)
		return nil
	}
	var ret = new(map[string]interface{})
	if err := json.Unmarshal(body, ret); err != nil {
		panic(err)
		return nil
	}
	return ret
}

func GetSpikeStat() *map[string]interface{} {
	res, err := http.Get("http://127.0.0.1:7013/manage/stat")
	if err != nil {
		return nil
	}
	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		panic(err)
		return nil
	}
	var ret = new(map[string]interface{})
	if err := json.Unmarshal(body, ret); err != nil {
		panic(err)
		return nil
	}
	return ret
}

func GetSpikeInit(b, e, tb, te, td string) *map[string]interface{} {
	res, err := http.Get("http://127.0.0.1:7013/manage/init/" + b + "/" + e + "/" + tb + "/" + te + "/" + td)
	if err != nil {
		// ctx.HTML(http.StatusOK, "spike-close.html", nil)
		return nil
	}
	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		panic(err)
		return nil
	}
	var ret = new(map[string]interface{})
	if err := json.Unmarshal(body, ret); err != nil {
		fmt.Println(string(body))
		panic(err)
		return nil
	}
	return ret
}

func GetSpikeClear() *map[string]interface{} {
	res, err := http.Get("http://127.0.0.1:7013/manage/clear")
	if err != nil {
		// ctx.HTML(http.StatusOK, "spike-close.html", nil)
		return nil
	}
	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		panic(err)
		return nil
	}
	var ret = new(map[string]interface{})
	if err := json.Unmarshal(body, ret); err != nil {
		panic(err)
		return nil
	}
	return ret
}
